
if exists (select 1 from sysobjects where name = 'set_personzeitennew' and type = 'P')
begin
   drop procedure set_personzeitennew
   print 'Procedure: set_personzeitennew deleted ...'
end
go

create procedure set_personzeitennew(
  @prsid         int   = 1,
  @oldjahrid     int   = 1
)
as
begin

   set nocount on

   declare @ferientage    decimal(5,2)
   declare @jahrid        int
   declare @proz          smallint

   declare @oldsaldo      decimal(5,2)
   declare @oldferien     decimal(5,2)

   select @jahrid = JahrID 
     from PlanungsJahr 
    where Status = 1
    
   if @jahrid is null select @jahrid = max(JahrID) from PlanungsJahr
   
   select @proz = ap.Prozent 
     from Arbeitspensum ap 
    where ap.Status = 1 
      and ap.PrsID = @prsid
      
   select @ferientage = isnull(Options.zahlwert,0) 
     from Options 
    where Options.typ = 'Ferientage' 
      and wert = 0

   select @oldsaldo = isnull(ArbeitszeitSaldo,0) 
     from PersonZeiten 
    where JahrID = @oldjahrid 
      and PrsID = @prsid
      
   select @oldferien = isnull(FerienSaldo,0) 
     from PersonZeiten 
    where JahrID = @oldjahrid 
      and PrsID = @prsid

   if not exists (select 1 from PersonZeiten where PrsID = @prsid and JahrID = @jahrid)
   begin
     insert into PersonZeiten
                 (PrsID, 
                  FerienSaldo, 
                  ArbeitszeitSaldo, 
                  JahrID) 
          values (@prsid,
                 ((@ferientage * ISNULL(@proz,100))/100) + isnull(@oldferien,0), 
                 isnull(@oldsaldo,0), 
                 @jahrid)
   end

end
go
print 'Procedure: set_personzeitennew done ...'
go
grant exec on set_personzeitennew to prsadmins with grant option
go
grant exec on set_personzeitennew to prsusers
go

